package org.jeecg.common.job.data.dao;

import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.constant.enums.FlagEnum;
import org.jeecg.common.datasource.jdbc.BaseDao;
import org.jeecg.common.datasource.jdbc.vo.PageInfo;
import org.jeecg.common.datasource.jdbc.vo.PageSort;
import org.jeecg.common.job.data.vo.JobInfoVo;
import org.jeecg.common.job.enums.JobConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author zhaoguoqiang
 * @version 2020年01月19 15:58
 */
@Component
public class JobInfoDao extends BaseDao {

    private static final Logger LG = LoggerFactory.getLogger("Job");

    /**
     * 根据ID获取任务信息
     *
     * @param id 任务ID
     * @return Job
     */
    public JobInfoVo load(String id) {
        return this.load(JobInfoVo.class, id);
    }

    /**
     * 添加
     *
     * @param job 任务对象
     */
    public String save(JobInfoVo job) {
        job.setCreateTime(new Date());
        job.setUpdateTime(new Date());
        String id = this.insertIntoTable(job);
        return id;
    }

    /**
     * 编辑
     *
     * @param job       任务对象
     * @param fieldName 更新字段
     */
    public void update(JobInfoVo job, String... fieldName) {
        this.updateInclude(job, fieldName);
    }

    /**
     * 删除数据
     *
     * @param id 任务ID
     */
    public int delete(String id) {
        String sql = "update sys_job_config set del_sign = ? where id = ?";
        return this.jdbc.update(sql, FlagEnum.YES.getId(), id);
    }

    /**
     * 分页查询定时任务
     *
     * @param pageSort 分页排序信息
     * @param name  任务名称
     * @return
     */
    public PageInfo<JobInfoVo> getJobPage(PageSort pageSort, String name) {
        String sql = "select * from sys_job_config where del_sign = ? ";
        List<Object> params = new ArrayList<>();
        params.add(FlagEnum.NO.getId());
        if (StringUtils.isNotBlank(name)) {
            sql += "and name like ? ";
            params.add("%" + name + "%");
        }
        return this.findByPage(sql, params.toArray(new Object[0]), JobInfoVo.class, pageSort);
    }

    /**
     * 查询定时任务
     *
     * @return
     */
    public List<JobInfoVo> getJobList() {
        String sql = "select * from sys_job_config where del_sign = ? and status = ?";
        return this.findByList(sql, JobInfoVo.class, FlagEnum.NO.getId(), JobConstants.JobStatus.NO.getId());
    }

    @Override
    public boolean isFieldDuplicate(String table, String fieldName, Object value, String where) {
        return super.isFieldDuplicate(table, fieldName, value, where);
    }

    public JobInfoVo findJobInfoVo(String beanName, String beanMethod){
        String sql = "select * from sys_job_config where bean_name = ? and bean_method = ?";
        return this.findOne(sql, JobInfoVo.class, beanName, beanMethod);
    }
}
